package org.vectrics.recruiter.struts.admin.file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Category;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.vectrics.SystemException;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.document.CandidateDocument;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;

/**
 * @author pgoette
 * Clase que muestra el load de archivos
 */
public class FileUpLoadAction extends Action{

	private static Category log = Category.getInstance(FileUpLoadAction.class);
	
	protected Person getPersonWithResume(HttpServletRequest request, FileForm resumeForm) {
		String userId = request.getParameter("userId");
		Person person = null;
		if (userId == null) {
			userId = resumeForm.getIdPerson();
		}
		
		if (userId == null) {
			throw new SystemException("'userId' parameter not found while uploading resume");
		}
		person = CoreServiceLocator.getPersonService().findPersonById(new Long(userId));
		return(person);
	}
	
	
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    		HttpServletRequest request, HttpServletResponse response)
    		throws Exception {
    			
		boolean illegalFileType = false;
		// Tomo el formulario
		FileForm fileForm = (FileForm)form;
		// Busco la persona
		Person personWithResume = this.getPersonWithResume(request, fileForm);
		request.getSession(true).setAttribute("userId", personWithResume.getId().toString());
		
		// Busco el archivo
		org.apache.struts.upload.FormFile file = fileForm.getTheFile();
		
		log.info("execute() - uploading resume for user: " + personWithResume);
		// Obtengo el nombre del archivo
		String fileName = file.getFileName();
		log.info("File Name = " + fileName);
		log.info("File Size = " + file.getFileSize());
		// Obtengo la categoria
		String categoryCode = fileForm.getCategory();
		
		// Si la categoria es nula le pongo desconocido.
		if (categoryCode==null){
			categoryCode = CandidateDocument.UNKNOWN_TYPE;
		}
		
		// Valido el archivo
		if (file.getFileSize() > 60000000) {
			return mapping.findForward("illegalfile");
		}
		
		if (fileName.endsWith("pdf")) {
		}
		else if (fileName.endsWith("txt")) {
		}
		else if (fileName.endsWith("doc")) {
		}
		else {
			illegalFileType = true;
		}
		
		// Obtengo el nombre del archivo
		String resumeName = fileForm.getName();
		if (resumeName == null) {
			resumeName = "Uploaded File";
		} 
		//		File uploadedFile = new File(resumeDir + "/" + resume.getId() + ".doc");
		if (!illegalFileType) {
			try {
				// Guardo el archivo y genero un registro en CandidateDocument. 
				// CandidateDocument es un objeto que sirve para guardar documentos de la persona, su nombre fue heredado de vectrics.
				InputStream uploadStream = file.getInputStream();
				UploadFileHelper helper = new UploadFileHelper();
				String originalFileName = file.getFileName();
				helper.execute(uploadStream, resumeName, categoryCode, originalFileName, personWithResume);
			} catch (FileNotFoundException fne) {
				throw new SystemException("File not found", fne);
			} catch (IOException ioe) {
				throw new SystemException("IO Exception", ioe);
			}
			return mapping.findForward("success");
		}
		else {
			return mapping.findForward("illegalfile");
		}

    }

    protected boolean wasButtonPressed(Request request, String name) {
	    boolean result = false;
	    String paramValue = request.getParameter(name);
	    if (paramValue == null) {
	        paramValue = request.getParameter(name + ".x");
	    }
	    if (paramValue != null)
	        result = true;
	    return(result);
	}	
	
}
